﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Devonline.Core;
using Devonline.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Web.Models;

namespace Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<OrdersController> _logger;
        public OrdersController(ApplicationDbContext context, ILogger<OrdersController> logger)
        {
            _context = context;
            _logger = logger;
        }

        [HttpGet]
        [EnableQuery]
        public IActionResult Get()
        {
            _logger.LogInformation("user {user} query the order list", User.Identity.Name);
            return Ok(_context.Orders);
        }

        [HttpPost]
        public async Task<IActionResult> InsertAsync(Order order)
        {
            _logger.LogInformation("user {user} will add the order {order}", User.Identity.Name, order);

            order.Create(User.Identity.Name);
            order.OrderTime = DateTime.UtcNow;
            if (order.OrderDetails != null)
            {
                foreach (var orderDetail in order.OrderDetails)
                {
                    orderDetail.OrderId = order.Id;
                    orderDetail.Create(User.Identity.Name);
                    _context.OrderDetails.Add(orderDetail);
                }
            }

            order.Amount = order.OrderDetails.Sum(x => x.Price * x.Count);
            _context.Orders.Add(order);

            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to add the order {order}", User.Identity.Name, order);
                return Ok();
            }

            return BadRequest($"创建订单 {order.ToJsonString()} 没有成功!");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> ChangeAsync(string id, Order viewModel)
        {
            _logger.LogInformation("user {user} will change the order {order}", User.Identity.Name, id);
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }

            viewModel.CopyTo(order);

            _context.Orders.Update(order);

            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to change the order {order}", User.Identity.Name, order);
                return Ok();
            }

            return BadRequest($"修改订单 {viewModel.ToJsonString()} 没有成功!");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAsync(string id)
        {
            _logger.LogInformation("user {user} will delete the order {order}", User.Identity.Name, id);
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }

            if (order.OrderDetails != null)
            {
                foreach (var orderDetail in order.OrderDetails)
                {
                    _context.OrderDetails.Remove(orderDetail);
                }
            }

            _context.Orders.Remove(order);
            var result = await _context.SaveChangesAsync();
            if (result >= 1)
            {
                _logger.LogWarning("user {user} success to delete the order {order}", User.Identity.Name, order);
                return Ok();
            }

            return BadRequest($"删除订单 {order.ToJsonString()} 出错!");
        }
    }
}
